package project.sample.nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * @author: WUZH009
 * @date: 2019/8/23 16:23
 **/
public class NioClient {
    public static void main(String[] args) {
        try {
            Selector selector = Selector.open();
            SocketChannel channel = SocketChannel.open();
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
            channel.connect(new InetSocketAddress("localhost", 8890));
            String req = "GET / HTTP/1.1\n" +
                    "Host: localhost:8890\n" +
                    "Connection: keep-alive\n" +
                    "Upgrade-Insecure-Requests: 1\n" +
                    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36\n" +
                    "Sec-Fetch-Mode: navigate\n" +
                    "Sec-Fetch-User: ?1\n" +
                    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\n" +
                    "Sec-Fetch-Site: none\n" +
                    "Accept-Encoding: gzip, deflate, br\n" +
                    "Accept-Language: zh-CN,zh;q=0.9\n\n";
            channel.write(ByteBuffer.wrap(req.getBytes()));
            selector.select();
            ByteBuffer buffer = ByteBuffer.allocate(8192);
            Thread.sleep(1000L);
            channel.read(buffer);
            buffer.flip();
            System.out.println(new String(buffer.array()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
